package com.indexingsystem.system.service.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.indexingsystem.boss.Vo.BooksReqVo;
import com.indexingsystem.boss.Vo.BooksTableVo;
import com.indexingsystem.boss.Vo.BooksVo;
import com.indexingsystem.boss.Vo.ResCategoryRelationsVo;
import com.indexingsystem.boss.admin.mapper.AuditLogsMapper;
import com.indexingsystem.boss.admin.mapper.BooksMapper;
import com.indexingsystem.boss.admin.mapper.DhResourceauditlogsMapper;
import com.indexingsystem.boss.admin.mapper.IdhTodayStorageInfosMapper;
import com.indexingsystem.boss.admin.mapper.ResCategoryRelationsMapper;
import com.indexingsystem.boss.admin.mapper.ResourceRelationsMapper;
import com.indexingsystem.boss.admin.mapper.ResourceTypeMapper;
import com.indexingsystem.boss.admin.mapper.ResourcesMapper;
import com.indexingsystem.boss.admin.mapper.SpecialResourceDatasMapper;
import com.indexingsystem.boss.common.PagedResult;
import com.indexingsystem.boss.entity.AuditLogs;
import com.indexingsystem.boss.entity.Books;
import com.indexingsystem.boss.entity.DhResourceauditlogs;
import com.indexingsystem.boss.entity.DhTodayStorageInfos;
import com.indexingsystem.boss.entity.ResCategoryRelations;
import com.indexingsystem.boss.entity.ResourceCategors;
import com.indexingsystem.boss.entity.ResourceRelations;
import com.indexingsystem.boss.entity.ResourceType;
import com.indexingsystem.boss.entity.ResourceUpdateRecord;
import com.indexingsystem.boss.entity.Resources;
import com.indexingsystem.boss.entity.SpecialResourceDatas;
import com.indexingsystem.boss.utils.BeanUtils;
import com.indexingsystem.boss.utils.DateUtil;
import com.indexingsystem.boss.utils.InstitutionLoadUtils;
import com.indexingsystem.boss.utils.StringUtil;
import com.indexingsystem.db.mongoDB.impl.BooksResourceMongo;
import com.indexingsystem.db.mongoDB.impl.ResourceCategorsResListMongo;
import com.indexingsystem.db.mongoDB.po.BooksResourceMongoVo;
import com.indexingsystem.db.mongoDB.po.ResourceCategorsResPo;
import com.indexingsystem.system.service.IBooksService;
import com.indexingsystem.system.service.IResourceCategorsService;
import com.indexingsystem.system.service.IResourceUpdateRecordService;

@Service
public class BooksServiceImpl implements IBooksService {

	@Resource
	private BooksMapper						booksMapper;
	@Resource
	private ResourcesMapper					resourcesMapper;
	@Resource
	private ResCategoryRelationsMapper		resCategoryRelationsMapper;
	@Resource
	private SpecialResourceDatasMapper		specialResourceDatasMapper;

	@Resource
	private AuditLogsMapper					auditLogsMapper;

	@Resource
	private IdhTodayStorageInfosMapper		idhTodayStorageInfosMapper;

	@Resource
	private DhResourceauditlogsMapper		dhResourceauditlogsMapper;

	@Resource
	private ResourceRelationsMapper			resourceRelationsMapper;

	@Resource
	private ResourceTypeMapper				resourceTypeMapper;

	@Resource
	private IResourceUpdateRecordService	iResourceUpdateRecordService;

	@Resource
	private IResourceCategorsService		iResourceCategorsService;

	@Override
	public int deleteByPrimaryKey(String resId) {
		return booksMapper.deleteByPrimaryKey( resId );
	}

	@Override
	public int insertSelective(Books record) {
		return booksMapper.insertSelective( record );
	}

	@Override
	public PagedResult<BooksTableVo> selectBooksList(BooksVo booksVo) {
		Integer pageNo = booksVo.getPageNumber() == null ? 0 : booksVo.getPageNumber();
		Integer pageSize = booksVo.getPageSize() == null ? 10 : booksVo.getPageSize();

		List<BooksTableVo> booksTableVoList = BooksResourceMongo.findBooksByPage( booksVo, InstitutionLoadUtils.getString( "institutionId" ) );
		// startPage是告诉拦截器说我要开始分页了。分页参数是这两个。
		PageHelper.startPage( pageNo, pageSize );
		if (null != booksTableVoList && booksTableVoList.size() > 0) {
			return BeanUtils.toPagedResult( booksTableVoList );
		} else {
			return BeanUtils.toPagedResult( booksMapper.selectBooksList( booksVo ) );
		}
	}

	@Override
	public Books selectByPrimaryKey(String resId) {
		return booksMapper.selectByPrimaryKey( resId );
	}

	@Override
	public int updateByPrimaryKeySelective(Books record) {
		return booksMapper.updateByPrimaryKeySelective( record );
	}

	@Override
	public List<BooksVo> searchBooksList(BooksVo record) {
		return booksMapper.searchBooksList( record );
	}

	@Override
	public Integer getBooksListCount(BooksVo record) {
		Integer maxCount = 0;

		maxCount = BooksResourceMongo.findBooksMaxCount( record, InstitutionLoadUtils.getString( "institutionId" ) );
		if (maxCount == 0) {
			maxCount = booksMapper.getBooksListCount( record );
		}
		return maxCount;
	}

	@Override
	public int addBooksInfo(BooksReqVo booksReqVo, AuditLogs auditLogs, DhTodayStorageInfos dhTodayStorageInfos, DhResourceauditlogs resourceauditlogs)
			throws Exception {
		int result = 0;
		BooksResourceMongoVo booksResourceMongoVo = new BooksResourceMongoVo();
		if (null != booksReqVo) {
			Resources resources = booksReqVo.getResources();
			if (null != resources) {
				booksResourceMongoVo.setResId( resources.getResId() );
				booksResourceMongoVo.setResTypeId( resources.getResTypeId() );
				booksResourceMongoVo.setResTable( "Books" );

				resourcesMapper.insertSelective( resources );
				booksResourceMongoVo.setResources( resources );
			}
			Books books = booksReqVo.getBooks();
			if (null != books) {
				result = booksMapper.insertSelective( books );
				booksResourceMongoVo.setBooks( books );
			}
			ResCategoryRelations resCategoryRelation = null;
			List<ResCategoryRelations> resultResCategoryRelationsList = null;
			List<ResCategoryRelationsVo> resCategoryRelationsVoList = booksReqVo.getResCategoryRelationsList();
			if (null != resCategoryRelationsVoList && resCategoryRelationsVoList.size() > 0) {
				resultResCategoryRelationsList = new ArrayList<ResCategoryRelations>();
				for (ResCategoryRelationsVo resCategoryRela : resCategoryRelationsVoList) {
					resCategoryRelation = new ResCategoryRelations();
					resCategoryRelation.setResCategoryRelationId( resCategoryRela.getResCategoryRelationId() );
					resCategoryRelation.setResCategoryId( resCategoryRela.getResCategoryId() );
					resCategoryRelation.setResId( resCategoryRela.getResId() );
					if (!resultResCategoryRelationsList.contains( resCategoryRelation )) {
						resultResCategoryRelationsList.add( resCategoryRelation );
					}
				}
			}
			if (null != resultResCategoryRelationsList && resultResCategoryRelationsList.size() > 0) {
				resCategoryRelationsMapper.insertResCategoryRelationsBatch( resultResCategoryRelationsList );
				for (ResCategoryRelationsVo resCategoryRela : resCategoryRelationsVoList) {
					// 登记资源分类资源变更表
					// 记录接触关系的资源
					ResourceUpdateRecord resourceUpdateRecord = new ResourceUpdateRecord();
					resourceUpdateRecord.setResourceUpdateRecordId( StringUtil.createSystemDataPrimaryKey() );
					resourceUpdateRecord.setResId( resCategoryRela.getResId() );
					ResourceType resType = resourceTypeMapper.selectResourceTypeResTableExits( "Books" );
					resourceUpdateRecord.setResTable( resType.getResTable() );
					resourceUpdateRecord.setResTypeId( resType.getResTypeId() );
					resourceUpdateRecord.setSuperCategoryId( resCategoryRela.getParentId() );
					resourceUpdateRecord.setResourceCategoryId( resCategoryRela.getResCategoryId() );
					resourceUpdateRecord.setOperatedate( DateUtil.getCurDate_YYYY_MM_DD() );
					resourceUpdateRecord.setState( "1" );
					iResourceUpdateRecordService.insert( resourceUpdateRecord );
				}

				booksResourceMongoVo.setResCategoryRelationsList( resultResCategoryRelationsList );

				// 报刊缓存mongo
				List<ResourceCategorsResPo> resourceCategorsResPoList = null;
				if (null != resultResCategoryRelationsList && resultResCategoryRelationsList.size() > 0) {
					resourceCategorsResPoList = new ArrayList<ResourceCategorsResPo>();
					for (ResCategoryRelations resCategoryRelations : resultResCategoryRelationsList) {
						ResourceCategorsResPo resourceCategorsResPo = new ResourceCategorsResPo();
						resourceCategorsResPo.setThumbnail( books.getFrontCover() );
						resourceCategorsResPo.setResType( 2 );
						String publishDate = resources.getPublishDate();

						resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( publishDate ) );
						resourceCategorsResPo.setPublishDate( publishDate );

						resourceCategorsResPo.setResId( resCategoryRelations.getResId() );
						resourceCategorsResPo.setResName( resources.getResName() );
						resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
						resourceCategorsResPo.setResTypeId( resources.getResTypeId() );
						resourceCategorsResPo.setResCategoryId( resCategoryRelations.getResCategoryId() );
						resourceCategorsResPo.setStatus( resources.getStatus() );

						// 通过资源分类id获取资源分类名称
						ResourceCategors resourceCategors = iResourceCategorsService.selectByPrimaryKey( resCategoryRelations.getResCategoryId() );
						resourceCategorsResPo.setResCategoryName( resourceCategors.getResName() );
						resourceCategorsResPo.setResTable( "Books" );

						if (!resourceCategorsResPoList.contains( resourceCategorsResPo )) {
							resourceCategorsResPoList.add( resourceCategorsResPo );
						}
					}
					ResourceCategorsResListMongo.addResourceCategorsResList( resourceCategorsResPoList, InstitutionLoadUtils.getString( "institutionId" ) );
				}

			}
			List<SpecialResourceDatas> specialResourceDatasList = booksReqVo.getSpecialResourceDatasList();
			if (null != specialResourceDatasList && specialResourceDatasList.size() > 0) {
				specialResourceDatasMapper.batchAddSpecialResourceDatas( specialResourceDatasList );
				booksResourceMongoVo.setDhSpecialResourceDatasList( specialResourceDatasList );
			}

			// 资源关系列表
			List<ResourceRelations> resourceRelationsList = resourceRelationsMapper.getResourceRelationsListByResId( booksReqVo.getResources()
					.getResId() );
			if (null != resourceRelationsList && resourceRelationsList.size() > 0) {
				booksResourceMongoVo.setDhResourceRelationsList( resourceRelationsList );
			}

			auditLogsMapper.insertSelective( auditLogs );
			booksResourceMongoVo.setAuditLogs( auditLogs );

			dhResourceauditlogsMapper.insertSelective( resourceauditlogs );
			booksResourceMongoVo.setResourceauditlogs( resourceauditlogs );

			idhTodayStorageInfosMapper.insert( dhTodayStorageInfos );
			booksResourceMongoVo.setTodayStorageInfos( dhTodayStorageInfos );
			BooksResourceMongo.addBooks( booksResourceMongoVo, InstitutionLoadUtils.getString( "institutionId" ) );
		}
		return result;
	}

	@Override
	public int updateBooksInfo(BooksReqVo booksReqVo) throws Exception {
		int result = 0;
		BooksResourceMongoVo booksResourceMongoVo = new BooksResourceMongoVo();
		if (null != booksReqVo) {
			Resources resources = booksReqVo.getResources();
			if (null != resources) {
				booksResourceMongoVo.setResId( resources.getResId() );
				booksResourceMongoVo.setResTypeId( resources.getResTypeId() );
				booksResourceMongoVo.setResTable( "Books" );

				resourcesMapper.updateByPrimaryKeySelective( resources );
				Resources queryRes = resourcesMapper.selectByPrimaryKey( resources.getResId() );
				booksResourceMongoVo.setResources( queryRes );
			}
			Books books = booksReqVo.getBooks();
			if (null != books) {
				result = booksMapper.updateByPrimaryKeySelective( books );
				Books queryBooks = booksMapper.selectByPrimaryKey( books.getResId() );
				booksResourceMongoVo.setBooks( queryBooks );
			}
			ResCategoryRelations resCategoryRelation = null;
			List<String> resIdList = null;
			List<String> resCategoryIdList = null;
			List<ResCategoryRelations> resultResCategoryRelationsList = null;
			List<ResCategoryRelationsVo> resCategoryRelationsVoList = booksReqVo.getResCategoryRelationsList();
			if (null != resCategoryRelationsVoList && resCategoryRelationsVoList.size() > 0) {
				resIdList = new ArrayList<String>();
				resCategoryIdList = new ArrayList<String>();
				resultResCategoryRelationsList = new ArrayList<ResCategoryRelations>();
				for (ResCategoryRelationsVo resCategoryRela : resCategoryRelationsVoList) {
					resCategoryRelation = new ResCategoryRelations();
					resCategoryRelation.setResCategoryRelationId( StringUtil.createSystemDataPrimaryKey() );
					resCategoryRelation.setResCategoryId( resCategoryRela.getResCategoryId() );
					resCategoryRelation.setResId( resCategoryRela.getResId() );
					resCategoryIdList.add( resCategoryRela.getResCategoryId() );
					resIdList.add( resCategoryRela.getResId() );

					if (!resultResCategoryRelationsList.contains( resCategoryRelation )) {
						resultResCategoryRelationsList.add( resCategoryRelation );
					}
				}
			}

			List<SpecialResourceDatas> specialResourceDatasList = booksReqVo.getSpecialResourceDatasList();
			if (null != specialResourceDatasList && specialResourceDatasList.size() > 0) {
				if (null != resIdList && resIdList.size() > 0) {
					// 终端先删后加
					specialResourceDatasMapper.deleteSpecialResourceDatasByIdBatch( resIdList );
				}
				specialResourceDatasMapper.batchAddSpecialResourceDatas( specialResourceDatasList );
				booksResourceMongoVo.setDhSpecialResourceDatasList( specialResourceDatasList );
			}

			if (null != resIdList && resIdList.size() > 0) {
				// 先删后加
				resCategoryRelationsMapper.deleteResBatchCategoryRelationsByResId( resIdList );
				if (null != resultResCategoryRelationsList && resultResCategoryRelationsList.size() > 0) {
					// 后加
					resCategoryRelationsMapper.insertResCategoryRelationsBatch( resultResCategoryRelationsList );
					for (ResCategoryRelations resCategoryRelations : resultResCategoryRelationsList) {
						// 登记资源分类资源变更表
						// 记录接触关系的资源
						ResourceUpdateRecord resourceUpdateRecord = new ResourceUpdateRecord();
						resourceUpdateRecord.setResourceUpdateRecordId( StringUtil.createSystemDataPrimaryKey() );
						resourceUpdateRecord.setResId( resCategoryRelations.getResId() );
						ResourceType resType = resourceTypeMapper.selectResourceTypeResTableExits( "Books" );
						resourceUpdateRecord.setResTable( resType.getResTable() );
						resourceUpdateRecord.setResTypeId( resType.getResTypeId() );
						ResourceCategors resourceCategors = iResourceCategorsService.selectByPrimaryKey( resCategoryRelations.getResCategoryId() );
						resourceUpdateRecord.setSuperCategoryId( resourceCategors.getParentId() );
						resourceUpdateRecord.setResourceCategoryId( resCategoryRelations.getResCategoryId() );
						resourceUpdateRecord.setOperatedate( DateUtil.getCurDate_YYYY_MM_DD() );
						resourceUpdateRecord.setState( "1" );
						iResourceUpdateRecordService.insert( resourceUpdateRecord );
					}
					booksResourceMongoVo.setResCategoryRelationsList( resultResCategoryRelationsList );
				}

				// 先通过resId清理所有分类列表
				List<String> delResIdList = new ArrayList<String>();
				delResIdList.add( resources.getResId() );
				ResourceCategorsResListMongo.deleteResCategoryRelationsByResId( delResIdList, InstitutionLoadUtils.getString( "institutionId" ) );

				// 重新缓存新的资源分类关系
				List<ResourceCategorsResPo> resourceCategorsResPoList = null;
				if (null != resultResCategoryRelationsList && resultResCategoryRelationsList.size() > 0) {
					resourceCategorsResPoList = new ArrayList<ResourceCategorsResPo>();
					for (ResCategoryRelations resCategoryRelations : resultResCategoryRelationsList) {
						ResourceCategorsResPo resourceCategorsResPo = new ResourceCategorsResPo();
						resourceCategorsResPo.setThumbnail( books.getFrontCover() );
						resourceCategorsResPo.setResType( 2 );
						String publishDate = resources.getPublishDate();

						resourceCategorsResPo.setDatePx( DateUtil.parseFormatToPublishDate( publishDate ) );
						resourceCategorsResPo.setPublishDate( publishDate );

						resourceCategorsResPo.setResId( resCategoryRelations.getResId() );
						resourceCategorsResPo.setResName( resources.getResName() );
						resourceCategorsResPo.setPublishDate( resources.getPublishDate() );
						resourceCategorsResPo.setResTypeId( resources.getResTypeId() );
						resourceCategorsResPo.setResCategoryId( resCategoryRelations.getResCategoryId() );
						resourceCategorsResPo.setStatus( resources.getStatus() );

						// 通过资源分类id获取资源分类名称
						ResourceCategors resourceCategors = iResourceCategorsService.selectByPrimaryKey( resCategoryRelations.getResCategoryId() );
						resourceCategorsResPo.setResCategoryName( resourceCategors.getResName() );
						resourceCategorsResPo.setResTable( "Books" );

						if (!resourceCategorsResPoList.contains( resourceCategorsResPo )) {
							resourceCategorsResPoList.add( resourceCategorsResPo );
						}
					}
					ResourceCategorsResListMongo.addResourceCategorsResList( resourceCategorsResPoList, InstitutionLoadUtils.getString( "institutionId" ) );
				}
			}

			AuditLogs auditLogs = null;
			List<AuditLogs> auditLogsList = auditLogsMapper.getAuditLogsListByResId( booksReqVo.getResources().getResId() );
			if (null != auditLogsList && auditLogsList.size() > 0) {
				auditLogs = auditLogsList.get( 0 );
			}
			booksResourceMongoVo.setAuditLogs( auditLogs );

			DhResourceauditlogs dhResourceAuditLogs = dhResourceauditlogsMapper.getResAuditlogsByResId( booksReqVo.getResources().getResId() );
			booksResourceMongoVo.setResourceauditlogs( dhResourceAuditLogs );

			DhTodayStorageInfos dhTodayStorageInfos = null;
			List<DhTodayStorageInfos> todayStorageInfosList = idhTodayStorageInfosMapper.getDhTodayStorageInfosByResId( booksReqVo.getResources()
					.getResId() );
			if (null != todayStorageInfosList && todayStorageInfosList.size() > 0) {
				dhTodayStorageInfos = todayStorageInfosList.get( 0 );
			}
			booksResourceMongoVo.setTodayStorageInfos( dhTodayStorageInfos );

			// 资源关系列表
			List<ResourceRelations> resourceRelationsList = resourceRelationsMapper.getResourceRelationsListByResId( booksReqVo.getResources()
					.getResId() );
			if (null != resourceRelationsList && resourceRelationsList.size() > 0) {
				booksResourceMongoVo.setDhResourceRelationsList( resourceRelationsList );
			}

			BooksResourceMongo.updateBooks( booksResourceMongoVo, InstitutionLoadUtils.getString( "institutionId" ) );
		}
		return result;
	}

	@Override
	public int deleteBooksByIdBatch(List<String> resIdList) throws Exception {
		int result = 0;
		if (null != resIdList && resIdList.size() > 0) {
			for (String resId : resIdList) {
				Books queryBooks = selectByPrimaryKey( resId );
				if (null != queryBooks) {
					// 1、删除
					result += deleteByPrimaryKey( queryBooks.getResId() );
					// 第二步删除资源分类关系
					List<ResCategoryRelations> resCategoryRelationList = resCategoryRelationsMapper.getResCategoryRelationsListByResId( queryBooks
							.getResId() );
					for (ResCategoryRelations resCategoryRelations : resCategoryRelationList) {
						resourceRelationsMapper.deleteByPrimaryKey( resCategoryRelations.getResCategoryRelationId() );
						// 登记资源分类资源变更表
						// 记录接触关系的资源
						ResourceUpdateRecord resourceUpdateRecord = new ResourceUpdateRecord();
						resourceUpdateRecord.setResourceUpdateRecordId( StringUtil.createSystemDataPrimaryKey() );
						resourceUpdateRecord.setResId( resCategoryRelations.getResId() );
						ResourceType resType = resourceTypeMapper.selectResourceTypeResTableExits( "Books" );
						resourceUpdateRecord.setResTable( resType.getResTable() );
						resourceUpdateRecord.setResTypeId( resType.getResTypeId() );
						ResourceCategors resourceCategors = iResourceCategorsService.selectByPrimaryKey( resCategoryRelations.getResCategoryId() );
						resourceUpdateRecord.setSuperCategoryId( resourceCategors.getParentId() );
						resourceUpdateRecord.setResourceCategoryId( resCategoryRelations.getResCategoryId() );
						resourceUpdateRecord.setOperatedate( DateUtil.getCurDate_YYYY_MM_DD() );
						resourceUpdateRecord.setState( "0" );
						iResourceUpdateRecordService.insert( resourceUpdateRecord );
					}

					// 第三步删除资源关系
					// 资源关系列表
					List<ResourceRelations> queryResRelationsList = resourceRelationsMapper.getResourceRelationsListByResId( queryBooks.getResId() );
					for (ResourceRelations resRelations : queryResRelationsList) {
						resourceRelationsMapper.deleteByPrimaryKey( resRelations.getResRelationId() );
					}

					// 第四步：删除资源终端关系
					List<SpecialResourceDatas> tempSpecialResDataList = specialResourceDatasMapper.getSpecialResourceDataListByResId( queryBooks
							.getResId() );
					for (SpecialResourceDatas resSpecialDatas : tempSpecialResDataList) {
						specialResourceDatasMapper.deleteBySpecialResourceDataId( resSpecialDatas.getSpecialResDataId() );
					}

					// 5、删除审核日志表关系
					List<AuditLogs> auditLogsList = auditLogsMapper.getAuditLogsListByResId( queryBooks.getResId() );
					for (AuditLogs auditLogs : auditLogsList) {
						auditLogsMapper.deleteByPrimaryKey( auditLogs.getProductLogId() );
					}

					// 清理入库审核日志表关系
					DhResourceauditlogs dhResourceAuditLogs = dhResourceauditlogsMapper.getResAuditlogsByResId( queryBooks.getResId() );
					if (null != dhResourceAuditLogs) {
						dhResourceauditlogsMapper.deleteByPrimaryKey( dhResourceAuditLogs.getId() );
					}

					// 删除流水
					List<DhTodayStorageInfos> dhTodayStorageInfosList = idhTodayStorageInfosMapper.getDhTodayStorageInfosByResId( queryBooks
							.getResId() );
					for (DhTodayStorageInfos dhTodayStorageInfos : dhTodayStorageInfosList) {
						idhTodayStorageInfosMapper.deleteTodayStorageInfoById( dhTodayStorageInfos.getStorageId() );
					}

					resourcesMapper.deleteByPrimaryKey( queryBooks.getResId() );
				}

			}
			// 批量删除mongo图书\绘本缓存记录，通过resId in操作获取，批量删除
			BooksResourceMongo.deleteBooksByIds( resIdList, InstitutionLoadUtils.getString( "institutionId" ) );

			// 先清理资源所有分类关系
			ResourceCategorsResListMongo.deleteResCategoryRelationsByResId( resIdList,InstitutionLoadUtils.getString( "institutionId" ));
		}

		return result;
	}
}